import { Global, Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserController } from './user/user.controller';
import { UserService } from './user/user.service';
import { UserModule } from './user/user.module';
import { ConfigModule, ConfigService } from '@nestjs/config';
import * as Joi from 'joi';
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';
import { ConfigEnum } from './enum/config.enum';

const envFilePath = [`.env.${process.env.NODE_ENV || 'dev'}`, '.env'];
const validationSchema = Joi.object({
  DB_DATABASE: Joi.string().required(),
  DB_TYPE: Joi.string().allow('mysql', 'mogodb').required(),
  DB_HOST: Joi.alternatives()
    .try(Joi.string().ip(), Joi.string().domain())
    .required(),
  DB_PORT: Joi.number().default(3306),
  DB_USERNAME: Joi.string().required(),
  DB_PASSWORD: Joi.string().required(),
  DB_SYNC: Joi.boolean().default(false),
});
@Global()
@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true, envFilePath, validationSchema }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (config: ConfigService) => {
        return {
          type: config.get(ConfigEnum.DB_TYPE),
          database: config.get(ConfigEnum.DB_DATABASE),
          host: config.get(ConfigEnum.DB_HOST),
          port: config.get(ConfigEnum.DB_PORT),
          username: config.get(ConfigEnum.DB_USERNAME),
          password: config.get(ConfigEnum.DB_PASSWORD),
          entities: [__dirname + '/**/*.entity{.ts,.js}'],
          // entities: [User],
          retryAttempts: 5000,
          synchronize: config.get(ConfigEnum.DB_SYNC),
        } as TypeOrmModuleOptions;
      },
    }),
    UserModule,
  ],
  controllers: [AppController, UserController],
  providers: [AppService, UserService],
})
export class AppModule {}
